package security.core.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import security.debug.RBACLogger;

public class RBACFilterChain implements FilterChain {
	private FilterChain originalChain;
	private List<Filter> filters;
	private int position;
	
	public RBACFilterChain(List<Filter> filters, FilterChain chain) {
		if (RBACLogger.debug()) {
			RBACLogger.log("RBACFilterChain#constructor is called!");
		}
		this.originalChain = chain;
		this.filters = filters;
		position = 0;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response)
			throws IOException, ServletException {
		if (RBACLogger.debug()) {
			RBACLogger.log("RBACFilterChain#doFilter is called!");
		}
		// check if there is unused filter in the list
		if (position < filters.size()) {
			// get next filter and call doFilter function
			position++;
			filters.get(position - 1).doFilter(request, response, this);
		} else {
			// go back to the original chain
			originalChain.doFilter(request, response);
		}
	}
}
